<?php
class ContactFormBlock extends BlockComponent{
    public $id = 'contactform';

    public $adminEmail;

    /**
     * output
     */
    public function run(){
        parent::run();

        //load the post model
        $model = new ContactForm;
        if (isset($_POST['ContactForm'])) {
            $model->attributes = $_POST['ContactForm'];
            if ($model->validate()) {
                //

                //save model
                $contactUs = new ContactUs;
                $contactUs->attributes = $model->attributes;

                if($contactUs->save()){
                    //send the email to admin
                    $this->_sendEmail($model);

                    Yii::app()->user->setFlash('contact', 'Thank you for contacting us. We will respond to you as soon as possible.');
                }

                $this->controller->refresh();
            }
        }

        $this->render($this->outputView, array('model' => $model));
    }

    public function params() {
        return array(
            'adminEmail' => 'Admin Email'
        );
    }

    public function validate() {
        if(!filter_var($this->adminEmail, FILTER_VALIDATE_EMAIL)){
            $this->errors['adminEmail'] = 'Email not valid email address';

            return false;
        }
        return true;
    }


    private function _sendEmail($contactFormModel){
        //get email template
        $mailTemplate = db()->createCommand()
                ->select('*')
                ->from('{{email_templates}}')
                ->where('id = 10')
                ->queryRow();

        $body = str_replace(array('[MESSAGE]', '[SENDER]', '[NAME]', '[PHONE]', '[MAILSUBJECT]', '[IP]', '[SITE_NAME]', '[URL]'),
                array(
                    $contactFormModel->body,
                    $contactFormModel->email,
                    $contactFormModel->name,
                    $contactFormModel->phone,
                    $contactFormModel->subject,
                    $_SERVER['REMOTE_ADDR'],
                    'Contact',
                    bu()
                ),
                $mailTemplate['body']
        );

        //send mail to admin
        EmailHelper::send($this->adminEmail, 'Contact message', $body);
    }
}